package com.wwcom.darteagle.data;

import java.util.ArrayList;
import java.util.List;

import com.wwcom.darteagle.model.Match;
import com.wwcom.darteagle.model.MatchInfo;
import com.wwcom.darteagle.model.MatchPlayer;
import com.wwcom.darteagle.model.Player;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;
import android.util.Log;

public class MatchInfoObject extends DataObject {
    private static final String TABLE_NAME = "MATCHDATA";
    private static final String TABLE_CREATE =
            "CREATE TABLE " + TABLE_NAME + " (" +
            "MATCH_ID integer primary key autoincrement," +
            "MATCH_DATE integer," +
            "MATCH_PLAYERS text," +
            "MATCH_NSETS integer," +
            "MATCH_NLEGS integer," +
            "MATCH_LEGTARGET integer," +
            "MATCH_DOUBLEIN integer," +
            "MATCH_DOUBLEOUT integer," +
            "MATCH_TREBLEIN integer," +
            "MATCH_TREBLEOUT integer," +
            "MATCH_LOSERSTARTS integer," +
            "MATCH_LEGSCORE text," +
            "MATCH_SETSCORE text," +
            "MATCH_ISCOMPLETED integer" +
            ");";
    
    public MatchInfoObject(SQLiteDatabase database) {
    	super(database);
    }
    
	static public String createSQL() {
		return TABLE_CREATE;
	}

	static public String deleteSQL() {
		return "DROP TABLE IF EXISTS "+TABLE_NAME;
	}	
    
	static public String upgradeSQL(int oldVersion, int newVersion) {

		String sql= "";
		for (int i = oldVersion; i < newVersion; ++i) {
			int nextVersion = i + 1;
			switch (nextVersion) {
			// version 1 to version 2
			case 2:
				break;
			// version 2 to version 3
			case 3:
				// added MATCH_LOSERSTARTS column to MATCH
				sql += "alter table " + TABLE_NAME
						+ " add column MATCH_LOSERSTARTS integer default 0;";
				break;
			// version 3 to version 4
			case 4:
				// added MATCH_LOSERSTARTS column to MATCH
				sql += "alter table " + TABLE_NAME
						+ " add column MATCH_ISCOMPLETED integer default 0;";
				break;
			}
		}
		if (sql.equals(""))
			sql= null;
		return sql;
	}    
    
    
    public MatchInfo get(long matchId) {
    	Cursor cursor = database.query(TABLE_NAME, 
    			new String[] {"MATCH_ID","MATCH_DATE","MATCH_PLAYERS",
    			"MATCH_NSETS","MATCH_NLEGS","MATCH_LEGTARGET","MATCH_DOUBLEIN",
    			"MATCH_DOUBLEOUT","MATCH_TREBLEIN","MATCH_TREBLEOUT",
    			"MATCH_LEGSCORE","MATCH_SETSCORE","MATCH_LOSERSTARTS"}, 
    			"MATCH_ID="+matchId, null, null, null, "MATCH_DATE desc");
    	Log.d("MatchObject","Loading: "+matchId);
    	MatchInfo mi= new MatchInfo();
    	cursor.moveToNext(); //first record
    	String[] players= TextUtils.split(cursor.getString(cursor.getColumnIndex("MATCH_PLAYERS")),"#,#");
    	String[] legScore= TextUtils.split(cursor.getString(cursor.getColumnIndex("MATCH_LEGSCORE")),",");
    	String[] setScore= TextUtils.split(cursor.getString(cursor.getColumnIndex("MATCH_SETSCORE")),",");    	
    	for (String playerName : players) {
    		mi.addMatchPlayer(new Player(playerName));    		
    	}
    	int i= 0;
    	for (MatchPlayer mp : mi.getMatchPlayers()) {
    		mp.setNumLegs(Integer.parseInt(legScore[i]));
    		mp.setNumSets(Integer.parseInt(setScore[i]));
    		i++;
    	}
    	mi.setNumSets(cursor.getInt(cursor.getColumnIndex("MATCH_NSETS")));
    	mi.setNumLegs(cursor.getInt(cursor.getColumnIndex("MATCH_NLEGS")));
    	mi.setLegTarget(cursor.getInt(cursor.getColumnIndex("MATCH_LEGTARGET")));
    	mi.setDoubleIn(cursor.getInt(cursor.getColumnIndex("MATCH_DOUBLEIN")) == 1);
    	mi.setDoubleOut(cursor.getInt(cursor.getColumnIndex("MATCH_DOUBLEOUT")) == 1);
    	mi.setTrebleIn(cursor.getInt(cursor.getColumnIndex("MATCH_TREBLEIN")) == 1);
    	mi.setTrebleOut(cursor.getInt(cursor.getColumnIndex("MATCH_TREBLEOUT")) == 1);
    	mi.setLoserStarts(cursor.getInt(cursor.getColumnIndex("MATCH_LOSERSTARTS")) == 1);
    	
    	//set database id
    	mi.setId(matchId);
    	long date= cursor.getInt(cursor.getColumnIndex("MATCH_DATE"));
    	Log.d("MatchObject","Match Date: "+date);
    	mi.setDate(date*1000);
    	    	
    	return mi;
    }
    
    
    public void insert(Match m) {
    	    	
    	MatchInfo mi= m.getMatchInfo();
    	
    	ContentValues contentValues = new ContentValues();	
    	long date= mi.getDate();
    	contentValues.put("MATCH_DATE", (int)(date/1000));  //we only need seconds accuracy
    	List<MatchPlayer> mp= mi.getMatchPlayers();
    	String[] playerNames= new String[mp.size()];
    	int i= 0;
    	for (MatchPlayer p : mp) {
    		playerNames[i]= p.getPlayer().getName();
    		i++;
    	}        	
    	contentValues.put("MATCH_PLAYERS", escapeNoQuotes(
    			TextUtils.join("#,#",playerNames)) );
    	contentValues.put("MATCH_NSETS", mi.getNumSets() );
    	contentValues.put("MATCH_NLEGS", mi.getNumLegs() );
    	contentValues.put("MATCH_LEGTARGET", mi.getLegTarget() );
    	contentValues.put("MATCH_DOUBLEIN", mi.isDoubleIn() );
    	contentValues.put("MATCH_DOUBLEOUT", mi.isDoubleOut() );
    	contentValues.put("MATCH_TREBLEIN", mi.isTrebleIn() );
    	contentValues.put("MATCH_TREBLEOUT", mi.isTrebleOut() );
    	contentValues.put("MATCH_LOSERSTARTS", mi.isLoserStarts() );
    	contentValues.put("MATCH_ISCOMPLETED", m.isMatchComplete() );

    	long matchId= database.insert(TABLE_NAME, null, contentValues);
    	mi.setId(matchId);  //update database id

        String[] legScore= new String[mi.getMatchPlayers().size()];
        String[] setScore= new String[mi.getMatchPlayers().size()];
        i= 0;
        for (MatchPlayer p : mp) {
        	legScore[i]= Integer.toString(p.getNumLegs());
        	setScore[i]= Integer.toString(p.getNumSets());
        	i++;
        }
        contentValues = new ContentValues();
    	contentValues.put("MATCH_LEGSCORE", TextUtils.join(",",legScore) );
    	contentValues.put("MATCH_SETSCORE", TextUtils.join(",",setScore) );
        database.update(TABLE_NAME, contentValues, "MATCH_ID='" + matchId + "'", null);        
                
    	return;
    }

    public void delete(long matchId) {
    	database.delete(TABLE_NAME, "MATCH_ID=?", new String[] { Long.toString(matchId) });
    }

    
    public long getResumableId() {
    	Cursor cursor = database.query(TABLE_NAME, 
    			new String[] {"MATCH_ID"}, 
    			"MATCH_ISCOMPLETED=0", null, null, null, "MATCH_DATE desc");
    	if (cursor.getCount() < 1) {
    		return -1;
    	}
    	cursor.moveToNext(); //first record
    	return cursor.getLong(cursor.getColumnIndex("MATCH_ID"));
    }
    
    public boolean resumableExists() {
    	Cursor cursor = database.query(TABLE_NAME, new String[] {"MATCH_ID"}, "MATCH_ISCOMPLETED=0", null, null, null, null);
    	return cursor.getCount() > 0;
    }
    
    public void deleteAllResumable() {
    	database.delete(TABLE_NAME, "MATCH_ISCOMPLETED=0", null);
    }
        
    public List<MatchInfo> getPlayerMatchInfos(String playerName) {
    	List<MatchInfo> matches= new ArrayList<MatchInfo>();
    	
    	Cursor cursor = database.query(TABLE_NAME, 
    			new String[] {"MATCH_ID","MATCH_PLAYERS"}, 
    			"MATCH_ISCOMPLETED=1", null, null, null, "MATCH_DATE desc");  
    	while (cursor.moveToNext()) {
	    	String[] players= TextUtils.split(cursor.getString(cursor.getColumnIndex("MATCH_PLAYERS")),"#,#");
	    	boolean isPlayerMatch= false;
	    	for (String pn : players) {
	    		if (pn.equals(playerName))
	    			isPlayerMatch= true;
	    	}
	    	if (!isPlayerMatch)
	    		continue;
	    	
	    	long matchId= cursor.getLong(cursor.getColumnIndex("MATCH_ID"));
	    	matches.add(get(matchId));
    	}
    	
    	return matches;
    }

    
    
}
